import { Scene } from 'phaser'
import { useGameStore } from '../stores/gameStore'

export class GameScene extends Scene {
  private player!: Phaser.GameObjects.Sprite
  private enemies: Phaser.GameObjects.Sprite[] = []
  private map!: Phaser.Tilemaps.Tilemap
  private cursors!: Phaser.Types.Input.Keyboard.CursorKeys
  private gameStore = useGameStore()

  constructor() {
    super({ key: 'GameScene' })
  }

  preload() {
    // 加载游戏资源
    this.load.image('player', '/assets/images/player.png')
    this.load.image('enemy', '/assets/images/enemy.png')
    this.load.image('tileset', '/assets/images/tileset.png')
    this.load.image('health-potion', '/assets/images/health-potion.png')
    this.load.image('mana-potion', '/assets/images/mana-potion.png')
  }

  create() {
    // 创建地图
    this.createMap()

    // 创建玩家
    this.createPlayer()

    // 创建敌人
    this.createEnemies()

    // 创建UI
    this.createUI()

    // 设置碰撞检测
    this.setupCollisions()

    // 设置输入控制
    this.cursors = this.input.keyboard.createCursorKeys()
  }

  private createMap() {
    // 创建简单的瓦片地图
    this.map = this.make.tilemap({
      width: 20,
      height: 15,
      tileWidth: 32,
      tileHeight: 32,
    })

    const tileset = this.map.addTilesetImage('tileset')
    const groundLayer = this.map.createBlankLayer('ground', tileset, 0, 0)

    // 填充地面瓦片
    for (let x = 0; x < 20; x++) {
      for (let y = 0; y < 15; y++) {
        groundLayer.putTileAt(0, x, y)
      }
    }
  }

  private createPlayer() {
    this.player = this.add.sprite(400, 300, 'player')
    this.player.setScale(2)

    // 设置玩家物理属性
    this.physics.add.existing(this.player)
    ;(this.player.body as Phaser.Physics.Arcade.Body).setCollideWorldBounds(true)
  }

  private createEnemies() {
    // 创建几个敌人
    for (let i = 0; i < 3; i++) {
      const enemy = this.add.sprite(100 + i * 200, 100 + i * 100, 'enemy')
      enemy.setScale(1.5)
      this.physics.add.existing(enemy)
      this.enemies.push(enemy)
    }
  }

  private createUI() {
    // 创建玩家状态UI
    this.add.text(16, 16, '生命值: ' + this.gameStore.playerStats.health, {
      fontSize: '18px',
      color: '#ffffff',
      backgroundColor: '#000000',
      padding: { x: 10, y: 5 },
    })

    this.add.text(16, 50, '等级: ' + this.gameStore.playerStats.level, {
      fontSize: '18px',
      color: '#ffffff',
      backgroundColor: '#000000',
      padding: { x: 10, y: 5 },
    })

    this.add.text(16, 84, '分数: ' + this.gameStore.gameState.score, {
      fontSize: '18px',
      color: '#ffffff',
      backgroundColor: '#000000',
      padding: { x: 10, y: 5 },
    })
  }

  private setupCollisions() {
    // 设置玩家与敌人的碰撞
    this.physics.add.collider(
      this.player,
      this.enemies,
      this.handlePlayerEnemyCollision,
      undefined,
      this,
    )
  }

  private handlePlayerEnemyCollision(player: any, enemy: any) {
    // 处理玩家与敌人的碰撞
    this.gameStore.damagePlayer(10)
    console.log('玩家受到伤害，当前生命值:', this.gameStore.playerStats.health)
  }

  update() {
    this.handlePlayerMovement()
    this.updateEnemies()
  }

  private handlePlayerMovement() {
    const speed = 200
    const playerBody = this.player.body as Phaser.Physics.Arcade.Body

    if (this.cursors.left.isDown) {
      playerBody.setVelocityX(-speed)
    } else if (this.cursors.right.isDown) {
      playerBody.setVelocityX(speed)
    } else {
      playerBody.setVelocityX(0)
    }

    if (this.cursors.up.isDown) {
      playerBody.setVelocityY(-speed)
    } else if (this.cursors.down.isDown) {
      playerBody.setVelocityY(speed)
    } else {
      playerBody.setVelocityY(0)
    }
  }

  private updateEnemies() {
    // 简单的敌人AI：向玩家移动
    this.enemies.forEach((enemy) => {
      const enemyBody = enemy.body as Phaser.Physics.Arcade.Body
      const distance = Phaser.Math.Distance.Between(this.player.x, this.player.y, enemy.x, enemy.y)

      if (distance < 200) {
        // 敌人发现玩家，向玩家移动
        const angle = Phaser.Math.Angle.Between(enemy.x, enemy.y, this.player.x, this.player.y)

        const velocity = 100
        enemyBody.setVelocity(Math.cos(angle) * velocity, Math.sin(angle) * velocity)
      } else {
        // 敌人停止移动
        enemyBody.setVelocity(0, 0)
      }
    })
  }
}
